<?php
$this_file = str_replace( '\\', '/', __FILE__ );
$this_file = explode( 'wp-content', $this_file );
$this_file = $this_file[ 0 ];
require( $this_file . 'wp-blog-header.php' );
header( 'HTTP/1.1 200 OK' );

$aOptions            = SofaSuppaStore::initOptions( false );
$paypal_mode         = $aOptions[ 'paypal_mode' ];
$use_stock           = $aOptions[ 'use_stock' ];
$stock_notify_on_low = $aOptions[ 'stock_notify_on_low' ];
$stock_notify_email  = ( strlen( $aOptions[ 'stock_notify_email' ] ) > 6 ) ? $aOptions[ 'stock_notify_email' ] : NULL;
$num_of_mb           = $aOptions[ 'num_of_def_boxes' ];
if( $num_of_mb <= 0 ) $num_of_mb = 1;
global $wpdb;

// Include the paypal library
locate_template( array( 'gateways/Paypal.php' ), true, true );

// Create an instance of the paypal library
$myPaypal = new Paypal();

// Log the IPN results
$myPaypal->ipnLog = TRUE;

// Enable test mode if needed
if( $paypal_mode == 'sandbox' ) $myPaypal->enableTestMode();

// Check validity and write down it
if( $myPaypal->validateIpn() ) {
	
	$owner = get_userdata( 1 ); // to admin
	$to = $owner->user_email; // feele free change to: $to = 'recipient@domain.com'; :if required!
	
	// assign posted variables to local variables
	$txn_id = urldecode( stripslashes( $_POST[ 'txn_id' ] ) ); // OK
	$payment_amount = urldecode( stripslashes( $_POST[ 'mc_gross' ] ) ); // OK
	$receiver_email = urldecode( stripslashes( $_POST[ 'receiver_email' ] ) );
	$payment_date = current_time( mysql ); // OK
	$first_name = urldecode( stripslashes( $_POST[ 'first_name' ] ) );
	$last_name = urldecode( stripslashes( $_POST[ 'last_name' ] ) );
	$entire_name = $first_name . ' ' . $last_name; // OK
	$payer_status = urldecode( stripslashes( $_POST[ 'payer_status' ] ) ); // OK
	$custom = urldecode( stripslashes( $_POST[ 'custom' ] ) ); // OK
	$payer_email = urldecode( stripslashes( $_POST[ 'payer_email' ] ) ); // OK
	$contact_phone = urldecode( stripslashes( $_POST[ 'contact_phone' ] ) ); // OK
	$address_street = urldecode( stripslashes( $_POST[ 'address_street' ] ) ); // OK
	$address_zip = urldecode( stripslashes( $_POST[ 'address_zip' ] ) ); // OK
	$address_city = urldecode( stripslashes( $_POST[ 'address_city' ] ) ); // OK
	$address_country = urldecode( stripslashes( $_POST[ 'address_country' ] ) );
	$address_country_code = urldecode( stripslashes( $_POST[ 'address_country_code' ] ) );
	$entire_country = $address_country . ', ' . $address_country_code; // OK
	$mc_currency = urldecode( stripslashes( $_POST[ 'mc_currency' ] ) ); // OK
	$discount = urldecode( stripslashes( $_POST[ 'discount' ] ) ); // OK
	$mc_handling = urldecode( stripslashes( $_POST[ 'mc_handling' ] ) ); // OK
	$tax = urldecode( stripslashes( $_POST[ 'tax' ] ) ); // OK
	
	if( !$mc_handling || $mc_handling == '' ) $mc_handling = 0;
	if( !$discount || $discount == '' ) $discount = 0;
	
	$all_prices_only = array(); // save only prices to array
	$price_in_arr = explode( '^', $custom );
	$price_in_arr_len = count( $price_in_arr );
	if( $price_in_arr_len > 0 ) {
		$kkkkk = 0;
		while( $kkkkk < $price_in_arr_len ) {
			// 0 - name (ID), 1 - size, 2 - quantity, 3 - price, 4 - stock, 5 - shipp
			$resolve_item_arr = explode( '~', $price_in_arr[ $kkkkk ] );
			array_push( $all_prices_only, $resolve_item_arr[ 3 ] );
			$kkkkk ++;
		}
	}
	
	// how many items in the basket?
	// format as: ID~Product Name~Size~Quantity~Price~Individual Shipping Price^
	$num_cart_items = urldecode( stripslashes( $_POST[ 'num_cart_items' ] ) );
	// prepare custom for database save
	$iter_items = 1;
	$basket_string_full = '';
	while( $iter_items <= $num_cart_items ) {

		$basket_string_full .= ( urldecode( stripslashes( $_POST[ 'item_number' . $iter_items ] ) ) . '~' . 
								urldecode( stripslashes( $_POST[ 'item_name' . $iter_items ] ) ) . '~' . 
								urldecode( stripslashes( $_POST[ 'option_selection1_' . $iter_items ] ) ) . '~' . 
								urldecode( stripslashes( $_POST[ 'quantity' . $iter_items ] ) ) . '~' . 
								$all_prices_only[ $iter_items - 1 ] . '~' . 
								urldecode( stripslashes( $_POST[ 'mc_shipping' . $iter_items ] ) ) . '^' );
		$iter_items ++;
	}
	
    if( $myPaypal->ipnData['payment_status'] == 'Completed' ) {
		
        // file_put_contents('paypal.txt', 'SUCCESS');
		// insert to database
		
		$wpdb->insert( ( $wpdb->prefix . 'purchases_history' ), array( 'trans_date' => $payment_date, 'unique_code' => $txn_id, 'trans_status' => $payer_status, 'trans_basket' => $basket_string_full, 'user_name' => $entire_name, 'user_email' => $payer_email, 'user_phone' => $contact_phone, 'user_address' => $address_street, 'user_zip' => $address_zip, 'user_city' => $address_city, 'user_country' => $entire_country, 'currency' => $mc_currency, 'gross' => $payment_amount, 'discount' => $discount, 'handling' => $mc_handling, 'tax' => $tax, 'flag_shipped' => 0 ), array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) );
		
		// update stock inventory
		if( $custom != '' && $use_stock == 'yes' ) {
			
			$missing_products_arr = array();
			$notify_admin = FALSE;
			$serial_data = $custom;
			$arr_items_in_basket = explode( '^', $serial_data );
			array_pop( $arr_items_in_basket ); // remove last empty element
			$cnt_aiib = 0;
			$aiib_len = count( $arr_items_in_basket );
			
			if( $aiib_len > 0 ) {
				
				// proceed
				while( $cnt_aiib < $aiib_len ) {
				  
					$arr_sub_split_item = explode( '~', $arr_items_in_basket[ $cnt_aiib ] ); // 0 - name (ID), 1 - size, 2 - quantity, 3 - price, 4 - selected row, 5 - stock, 6 - shipp
					$single_id = intval( $arr_sub_split_item[ 0 ] );
					
					// get all required...
					$arr_sizes = array();
					$arr_stock = array();
					$kk = 0;
					while( $kk < $num_of_mb ) {
						$single_sizes = 'sofa_' . $kk . '_textarea_size';
						$single_stock = 'sofa_' . $kk . '_textarea_stock';
						array_push( $arr_sizes, get_post_meta( $single_id, $single_sizes, true ) );
						array_push( $arr_stock, get_post_meta( $single_id, $single_stock, true ) );
						$kk ++;
					}
					
					// check stock for real...
					$serach_size = trim( $arr_sub_split_item[ 1 ] );
					$pos_in_arr = array_search( (string)$serach_size, $arr_sizes ); // get the key for stock value
					$item_quantity = intval( $arr_sub_split_item[ 2 ] ); // quantity placed in buyer order
					$stock_calc = $arr_stock[ $pos_in_arr ] - $item_quantity; // calculate if stock fits
					
					// update meta
					update_post_meta( $single_id, 'sofa_' . $pos_in_arr . '_textarea_stock', $stock_calc );
					
					// notify or not?
					if( $stock_calc <= 0 && $stock_notify_on_low == 'yes' ) {
						array_push( $missing_products_arr, $single_id );
						$notify_admin = TRUE; // redundant...but it doesn't matter
					}
					
					$cnt_aiib ++;
				  
				}
			  
			}
		
		}
		
		// send notification upon purchase
		$subject = __( "Purchase made", "sofa_suppastore" ) . ', ' . get_bloginfo( 'name' );
		$message = __( "Just to let you know that your order has been received. On a side note, shopping and payment details will be sent by PayPal.", "sofa_suppastore" );
		$message .= '<br /><br />';
		$message .= __( "Thank you very much!", "sofa_suppastore" );
		$message .= '<br />' . home_url();
		$headers = "MIME-Version: 1.0\n" . "From: <$to>\n" . "Content-Type: text/html; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
		// send mail
		wp_mail( $payer_email, $subject, $message, $headers );
		
		// send notification if stock low
		if( $notify_admin && $stock_notify_on_low == 'yes' ) {
			// where to send notification?
			$owner = get_userdata( 1 );
			if( !$stock_notify_email ) $adminmail = $owner->user_email;
			else $adminmail = $stock_notify_email;
			// compose message
			$subject_sl = __( "Stock inventory low!", "sofa_suppastore" ) . ', ' . get_bloginfo( 'name' );
			$message_sl = __( "Just to let you know that certain items in your webshop are out of stock. Here's the report:", "sofa_suppastore" );
			$message_sl .= '<br /><br />';
			
			// make the list of stock low products
			if( count( $missing_products_arr ) > 0 ) {
				$cnt_mpa = 0;
				$len_mpa = count( $missing_products_arr );
				while( $cnt_mpa < $len_mpa ) {
					$product_obj = get_post( $missing_products_arr[ $cnt_mpa ] );
					$message_sl .= '<a href="' . get_permalink( $product_obj->ID ) . '">' . stripslashes( $product_obj->post_title ) . '</a><br />';
					$cnt_mpa ++;
				}
			}
			
			$message_sl .= '<br /><br />';
			$message_sl .= __( "Thank you very much!", "sofa_suppastore" );
			$message_sl .= '<br />' . home_url();
			$headers_sl = "MIME-Version: 1.0\n" . "From: <$to>\n" . "Content-Type: text/html; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
			// send mail
			wp_mail( $adminmail, $subject_sl, $message_sl, $headers_sl );
		}
		
				
    } else {
        //file_put_contents('paypal.txt', "FAILURE\n\n" . $myPaypal->ipnData);
		$subject = __( "Purchase not accepted", "sofa_suppastore" ) . ', ' . get_bloginfo( 'name' );
		$message = __( "PayPal did not accept your payment due to the fact your PayPal account is not valid. We are sorry but your order has to be disregarded.", "sofa_suppastore" );
		$message .= '<br /><br />';
		$message .= __( "Thank you very much!", "sofa_suppastore" );
		$message .= '<br />' . home_url();
		$headers = "MIME-Version: 1.0\n" . "From: <$to>\n" . "Content-Type: text/html; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
		// send mail
		wp_mail( $payer_email, $subject, $message, $headers );
    }
}